package com.clwl.supervise.superviseapp.controller.pro;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.clwl.supervise.superviseapp.config.RepeatSubmit;
import com.clwl.supervise.superviseapp.entity.base.SysDictData;
import com.clwl.supervise.superviseapp.entity.base.TsUser;
import com.clwl.supervise.superviseapp.entity.pro.*;
import com.clwl.supervise.superviseapp.entity.result.ResultEntity;
import com.clwl.supervise.superviseapp.entity.risk.JgPointDistance;
import com.clwl.supervise.superviseapp.service.base.BaseDataService;
import com.clwl.supervise.superviseapp.service.pro.*;
import com.clwl.supervise.superviseapp.util.UserHelper;
import com.clwl.supervise.superviseapp.util.file.FileResultEntity;
import com.clwl.supervise.superviseapp.util.file.FileUploadEnum;
import com.clwl.supervise.superviseapp.util.file.FileUploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Slf4j
@RestController
@RequestMapping("/pro/ratingScore")
public class JgProRatingScoreController {

    @Autowired
    private JgTcCompanyService jgTcCompanyService;

    @Autowired
    private BaseDataService baseDataService;

    @Autowired
    private JgFoodAdditiveTypeDetailMainService jgFoodAdditiveTypeDetailMainService;

    @Autowired
    private JgProStaticRiskContentMainService jgProStaticRiskContentMainService;

    @Autowired
    private JgProStaticScoreService jgProStaticScoreService;

    @Autowired
    private JgProStaticScoreFoodAdditiveTypeService jgProStaticScoreFoodAdditiveTypeService;

    @Autowired
    private JgProStaticScoreRiskContentService jgProStaticScoreRiskContentService;


    @Autowired
    private JgProDailyBonusPointsItemMainService jgProDailyBonusPointsItemMainService;

    @Autowired
    private JgProDynamicScoreBonusPointsItemService jgProDynamicScoreBonusPointsItemService;


    @Autowired
    private JgProDailyRandomCertFlightContentMainService jgProDailyRandomCertFlightContentMainService;

    @Autowired
    private JgProDynamicScoreRandomCertFlightContentService jgProDynamicScoreRandomCertFlightContentService;

    @Autowired
    private JgProDynamicScoreService jgProDynamicScoreService;

    @Autowired
    private JgProCompanyDailyScoreService jgProCompanyDailyScoreService;


    @Autowired
    private JgProDailyInspectionItemMainService jgProDailyInspectionItemMainService;

    @Autowired
    private JgProDailyInspectionContentMainService jgProDailyInspectionContentMainService;

    @Autowired
    private JgProDailyInspectionMissingMainService jgProDailyInspectionMissingMainService;


    @Autowired
    private JgProCompanyDailyScoreInspectionItemService jgProCompanyDailyScoreInspectionItemService;

    @Autowired
    private JgProCompanyDailyScoreInspectionContentService jgProCompanyDailyScoreInspectionContentService;

    @Autowired
    private JgProCompanyDailyScoreInspectionMissingService jgProCompanyDailyScoreInspectionMissingService;

    /**
     * 查询企业详细信息
     * */
    @GetMapping("getCompanyInfo")
    public ResultEntity<JgTcCompany> getCompanyInfo(Long companyId){
        JgTcCompany company = jgTcCompanyService.getById(companyId);
        JgPointDistance distance = baseDataService.getCheckDistance(companyId + "");
        company.setDistance(distance.getDistance());
        return ResultEntity.success(company);
    }

    /**
     * 查询企业详细信息
     * */
    @GetMapping("getResultTableCode")
    public ResultEntity<String> getResultTableCode(Long checkId,Long companyId){
        return ResultEntity.success(jgProCompanyDailyScoreService.getResultTableCode(checkId,companyId));
    }

    /**
     * 查询静态评分风险要素
     * */
    @GetMapping("getStaticRiskFactor")
    public ResultEntity<Map<String,Object>> getStaticRiskFactor(Long companyId){

        Map<String, Object> result = new HashMap<>();

        JgTcCompany company = jgTcCompanyService.getById(companyId);
        //根据企业生产食品类别编码 查询对应风险要素
        List<JgProFoodAdditiveTypeDetailMain> jgProFoodAdditiveTypeDetailMainList = jgFoodAdditiveTypeDetailMainService.selectFoodAdditiveTypeByTypeCode(Arrays.asList(company.getSplbbh().split(",")));
        //使用stream 流 获取 风险分值最高的要素 并设置标识
        Optional<JgProFoodAdditiveTypeDetailMain> maxScore = jgProFoodAdditiveTypeDetailMainList.stream()
                .max(Comparator.comparingDouble(JgProFoodAdditiveTypeDetailMain::getRiskScore));
        maxScore.ifPresent(jgProFoodAdditiveTypeDetailMain -> jgProFoodAdditiveTypeDetailMain.setIsMaximum("1"));
        result.put("foodAdditiveTypeList", jgProFoodAdditiveTypeDetailMainList);

        QueryWrapper<JgProStaticRiskContentMain> r = new QueryWrapper<>();
        r.eq("item_id", 1);//企业规模  初始数据 不可删除
        List<JgProStaticRiskContentMain> entSizeList = jgProStaticRiskContentMainService.list(r);
        result.put("entSizeList",entSizeList);

        QueryWrapper<JgProStaticRiskContentMain> r2 = new QueryWrapper<>();
        r2.eq("item_id", 2);//食品生产许可现查核查结果  初始数据 不可删除
        List<JgProStaticRiskContentMain> onsiteList = jgProStaticRiskContentMainService.list(r2);
        result.put("onsiteList",onsiteList);

        for(JgProStaticRiskContentMain onsite : onsiteList){
            if(onsite.getMinValue() < company.getDfl() && company.getDfl() <= onsite.getMaxValue()){
                onsite.setSelected("1");
            } else {
                onsite.setSelected("0");
            }
        }

        return ResultEntity.success(result);
    }


    @PostMapping("staticScore")
    @RepeatSubmit(lockTime = 10)
    public ResultEntity staticScore(@RequestBody JgProStaticScore jgProStaticScore){
        jgProStaticScore.setCreateBy(UserHelper.getUserInfo().getName());
        jgProStaticScore.setCreateTime(new Date());
        jgProStaticScoreService.staticScore(jgProStaticScore);
        return ResultEntity.success();
    }


    /**
     * 查询静态评分详情
     * */
    @GetMapping("getStaticScore")
    public ResultEntity<Map<String,Object>> getStaticScore(Long staticScoreId){
        Map<String, Object> result = new HashMap<>();
        JgProStaticScore staticScore = jgProStaticScoreService.getById(staticScoreId);
        result.put("staticScore",staticScore);
        //查询企业静态检查数据
        List<JgProStaticScoreFoodAdditiveType> scoreFoodAdditiveTypeList = jgProStaticScoreFoodAdditiveTypeService.staticScoreFoodAdditiveTypeListByStaticScoreId(staticScoreId);
        //使用stream 流 获取 风险分值最高的要素 并设置标识
        Optional<JgProStaticScoreFoodAdditiveType> maxScore = scoreFoodAdditiveTypeList.stream()
                .max(Comparator.comparingDouble(JgProStaticScoreFoodAdditiveType::getRiskScore));
        maxScore.ifPresent(scoreFoodAdditiveType -> scoreFoodAdditiveType.setIsMaximum("1"));
        result.put("scoreFoodAdditiveTypeList",scoreFoodAdditiveTypeList);

        // TODO 写死 查询 静态评分要素  之后有时间再研究改成动态

        QueryWrapper<JgProStaticScoreRiskContent> r = new QueryWrapper<>();
        r.eq("item_id", 1);//企业规模  初始数据 不可删除
        r.eq("static_score_id", staticScoreId);
        List<JgProStaticScoreRiskContent> entSizeList = jgProStaticScoreRiskContentService.list(r);
        result.put("entSizeList",entSizeList);

        QueryWrapper<JgProStaticScoreRiskContent> r2 = new QueryWrapper<>();
        r2.eq("item_id", 2);//食品生产许可现查核查结果  初始数据 不可删除
        r2.eq("static_score_id", staticScoreId);
        List<JgProStaticScoreRiskContent> onsiteList = jgProStaticScoreRiskContentService.list(r2);
        result.put("onsiteList",onsiteList);

        for(JgProStaticScoreRiskContent onsite : onsiteList){
            if(onsite.getMinValue() < staticScore.getDfl() && staticScore.getDfl() <= onsite.getMaxValue()){
                onsite.setSelected("1");
            } else {
                onsite.setSelected("0");
            }
        }

        return ResultEntity.success(result);
    }


    /**
     * 查询静态评分风险要素
     * */
    @GetMapping("getDynamicRiskFactor")
    public ResultEntity<Map<String,Object>> getDynamicRiskFactor(Long companyId){

        Map<String, Object> result = new HashMap<>();

        //查询该企业今年的日常检查数据 计算总分数
        QueryWrapper ds = new QueryWrapper<>();
        ds.eq("company_id", companyId);
        ds.eq("DATE_FORMAT(rating_date ,'%Y')", DateUtil.format(new Date(),"YYYY"));
        ds.eq("status", "1");
        List<JgProCompanyDailyScore> dailyScoreList = jgProCompanyDailyScoreService.list(ds);
        double dailyTotleScore = 0;
        for(JgProCompanyDailyScore dailyScore : dailyScoreList){
            dailyTotleScore += dailyScore.getDailyScore();
        }
        result.put("dailyTotleScore",dailyTotleScore);


        // TODO 写死 查询 动态评分要素  之后有时间再研究改成动态
        QueryWrapper sj = new QueryWrapper<>();
        sj.eq("item_id", 13);//双随机、一公开
        sj.orderByAsc("risk_score");
        List<JgProDailyRandomCertFlightContentMain> randomContentMainList = jgProDailyRandomCertFlightContentMainService.list(sj);
        result.put("randomContentMainList",randomContentMainList);

        QueryWrapper zh = new QueryWrapper<>();
        zh.eq("item_id", 14);//证后审查
        zh.orderByAsc("risk_score");
        List<JgProDailyRandomCertFlightContentMain> certContentMainList = jgProDailyRandomCertFlightContentMainService.list(zh);
        result.put("certContentMainList",certContentMainList);

        QueryWrapper fx = new QueryWrapper<>();
        fx.eq("item_id", 15);//飞行检查
        fx.orderByAsc("risk_score");
        List<JgProDailyRandomCertFlightContentMain> flightContentMainList = jgProDailyRandomCertFlightContentMainService.list(fx);
        result.put("flightContentMainList",flightContentMainList);

        //查询加分项
        QueryWrapper qw = new QueryWrapper();
        qw.eq("parent_id",0);
        qw.orderByAsc("serial_number");
        List<JgProDailyBonusPointsItemMain> bonusPointsItemMainList = jgProDailyBonusPointsItemMainService.list(qw);
        for(JgProDailyBonusPointsItemMain bonusPointsItemMain : bonusPointsItemMainList){
            QueryWrapper cqw = new QueryWrapper();
            cqw.eq("parent_id",bonusPointsItemMain.getId());
            cqw.orderByAsc("serial_number");
            List<JgProDailyBonusPointsItemMain> childrenList = jgProDailyBonusPointsItemMainService.list(cqw);
            bonusPointsItemMain.setChildrenList(childrenList);
        }
        result.put("bonusPointsItemMainList",bonusPointsItemMainList);

        return ResultEntity.success(result);
    }


    @PostMapping("dynamicScore")
    @RepeatSubmit(lockTime = 10)
    public ResultEntity dynamicScore(@RequestBody JgProDynamicScore jgProDynamicScore){
        jgProDynamicScore.setCreateBy(UserHelper.getUserInfo().getName());
        jgProDynamicScore.setCreateTime(new Date());
        jgProDynamicScoreService.dynamicScore(jgProDynamicScore);
        return ResultEntity.success();
    }


    /**
     * 查询静态评分详情
     * */
    @GetMapping("getDynamicScore")
    public ResultEntity<Map<String,Object>> getDynamicScore(Long dynamicScoreId){
        Map<String, Object> result = new HashMap<>();
        JgProDynamicScore dynamicScore = jgProDynamicScoreService.getById(dynamicScoreId);
        result.put("dynamicScore",dynamicScore);
        //查询动态风险因素
        QueryWrapper sj = new QueryWrapper<>();
        sj.eq("dynamic_score_id",dynamicScoreId);
        sj.eq("item_id", 13);//双随机、一公开
        sj.orderByAsc("risk_score");
        List<JgProDailyRandomCertFlightContentMain> randomContentMainList = jgProDynamicScoreRandomCertFlightContentService.list(sj);
        result.put("randomContentMainList",randomContentMainList);

        QueryWrapper zh = new QueryWrapper<>();
        zh.eq("dynamic_score_id",dynamicScoreId);
        zh.eq("item_id", 14);//证后审查
        zh.orderByAsc("risk_score");
        List<JgProDailyRandomCertFlightContentMain> certContentMainList = jgProDynamicScoreRandomCertFlightContentService.list(zh);
        result.put("certContentMainList",certContentMainList);

        QueryWrapper fx = new QueryWrapper<>();
        fx.eq("dynamic_score_id",dynamicScoreId);
        fx.eq("item_id", 15);//飞行检查
        fx.orderByAsc("risk_score");
        List<JgProDailyRandomCertFlightContentMain> flightContentMainList = jgProDynamicScoreRandomCertFlightContentService.list(fx);
        result.put("flightContentMainList",flightContentMainList);

        //查询加分项
        QueryWrapper qw = new QueryWrapper();
        qw.eq("parent_id",0);
        qw.eq("dynamic_score_id",dynamicScoreId);
        qw.orderByAsc("serial_number");
        List<JgProDynamicScoreBonusPointsItem> dynamicScoreBonusPointsItemList = jgProDynamicScoreBonusPointsItemService.list(qw);
        for(JgProDynamicScoreBonusPointsItem dynamicScoreBonusPointsItem : dynamicScoreBonusPointsItemList){
            //查询加分项
            QueryWrapper qw2 = new QueryWrapper();
            qw2.eq("parent_id",dynamicScoreBonusPointsItem.getItemId());
            qw2.eq("dynamic_score_id",dynamicScoreId);
            qw2.orderByAsc("serial_number");
            List<JgProDynamicScoreBonusPointsItem> childrenList = jgProDynamicScoreBonusPointsItemService.list(qw2);
            dynamicScoreBonusPointsItem.setChildrenList(childrenList);
        }
        result.put("bonusPointsItemMainList",dynamicScoreBonusPointsItemList);


        return ResultEntity.success(result);
    }


    @GetMapping("getDictByCode")
    public ResultEntity<List<SysDictData>> getDictByCode(String dictTypeCode){
        return ResultEntity.success(jgProDynamicScoreService.selectByDictTypeCode(dictTypeCode));
    }

    @GetMapping("getUserList")
    public ResultEntity<List<TsUser>> getUserList(Long deptId){
        return ResultEntity.success(jgProDynamicScoreService.selectByDeptId(deptId));
    }

    @GetMapping("getUserInfo")
    public ResultEntity<TsUser> getUserInfo(){
        return ResultEntity.success(UserHelper.getUserInfo());
    }

    @GetMapping("getDailyScoreList")
    public ResultEntity<List<JgProCompanyDailyScore>> getDailyScoreList(Long companyId){
        QueryWrapper<JgProCompanyDailyScore> r = new QueryWrapper<>();
        r.eq("company_id", companyId);
        r.eq("year", DateUtil.format(new Date(),"YYYY"));
        r.orderByAsc("serial_num");
        List<JgProCompanyDailyScore> dailyScoreList = jgProCompanyDailyScoreService.list(r);
        return ResultEntity.success(dailyScoreList);
    }


    @GetMapping("getDailyInspectionItemList")
    public ResultEntity<List<JgProDailyInspectionItemMain>> getDailyInspectionItemList(){
        //查询日常检查项 检查内容 合理缺项 信息
        QueryWrapper qwi = new QueryWrapper<>();
        qwi.orderByAsc("serial_number");
        List<JgProDailyInspectionItemMain> itemList = jgProDailyInspectionItemMainService.list(qwi);
        for(JgProDailyInspectionItemMain item : itemList){
            QueryWrapper qwc = new QueryWrapper<>();
            qwc.eq("inspection_item_id", item.getId());
            qwc.orderByAsc("serial_number");
            List<JgProDailyInspectionContentMain> contentList = jgProDailyInspectionContentMainService.list(qwc);
            item.setContentList(contentList);
            for(JgProDailyInspectionContentMain content : contentList){
                QueryWrapper qwm = new QueryWrapper<>();
                qwm.eq("inspection_content_id", content.getId());
                List<JgProDailyInspectionMissingMain> missingList = jgProDailyInspectionMissingMainService.list(qwm);
                for(JgProDailyInspectionMissingMain missing : missingList){
                    missing.setValue(missing.getId());
                    missing.setText(missing.getMissingContent());
                }
                content.setMissingList(missingList);
            }
        }
        return ResultEntity.success(itemList);
    }
    @RepeatSubmit
    @PostMapping("dailyScore")
    public ResultEntity dailyScore(@RequestBody JgProCompanyDailyScore dailyScore){
        jgProCompanyDailyScoreService.dailyScore(dailyScore);
        return ResultEntity.success();
    }



    /**
     * 上传图片
     *
     */
    @PostMapping("uploadImg")
    public ResultEntity uploadImg( MultipartFile file){
        try {
            FileResultEntity fileEntity = FileUploadUtil.uploadImage(file, FileUploadEnum.proFile.getPath());
            return ResultEntity.success(fileEntity);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error("图片上传失败");
        }

    }


    @GetMapping("dailyScoreInfo")
    public ResultEntity<HashMap<String,Object>> dailyScoreInfo(Long dailyScoreId){
        HashMap<String,Object> result = new HashMap<>();
        JgProCompanyDailyScore dailyScore = jgProCompanyDailyScoreService.getById(dailyScoreId);
        result.put("dailyScore",dailyScore);
        //查询日常检查项 检查内容 合理缺项 信息
        List<JgProCompanyDailyScoreInspectionItem> itemList =   jgProCompanyDailyScoreInspectionItemService.selectCompleteByCheckId(dailyScoreId);
        for(JgProCompanyDailyScoreInspectionItem item : itemList){
            List<JgProCompanyDailyScoreInspectionContent> contentList = jgProCompanyDailyScoreInspectionContentService.selectCompleteByCheckIdAndItem(item.getItemId(),dailyScoreId);
            item.setContentList(contentList);
            for(JgProCompanyDailyScoreInspectionContent content : contentList){
                List<JgProCompanyDailyScoreInspectionMissing> missingList = jgProCompanyDailyScoreInspectionMissingService.selectCompleteByCheckIdAndContentId(dailyScoreId,content.getContentId());
                for(JgProCompanyDailyScoreInspectionMissing missing : missingList){
                    missing.setValue(missing.getId());
                    missing.setText(missing.getMissingContent());
                    if("1".equals(missing.getSelected())){
                        content.setMissingValue(missing.getId());
                    }
                }
                content.setMissingList(missingList);
            }
        }
        result.put("itemList", itemList);
        return ResultEntity.success(result);
    }
}
